package com.jason.wsserver.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

public class EchoWebSocketHandler extends AbstractWebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(EchoWebSocketHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("New connection from {}", session.getRemoteAddress());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        //收到 ping 返回 pong
        if (message instanceof PingMessage) {
            PingMessage ping = (PingMessage) message;
            System.out.println("Received Ping");
            log.debug("Received Ping, payload {} bytes - replying Pong", ping.getPayload().capacity());
            session.sendMessage(new PongMessage(ping.getPayload()));
            return;
        }
        // 收到 text 返回 text
        if (message instanceof TextMessage) {
            TextMessage text = (TextMessage) message;
            String payload = text.getPayload();
            log.info("Received text: {}", payload);
            session.sendMessage(new TextMessage("Server received: " + payload));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.warn("Connection {} closed: {}", session.getId(), status);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("Transport error on session {}", session.getId(), exception);
    }
}